{% extends "base.html" %}

{% block title %}代码格式化工具 - 工具箱{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <h1 class="text-3xl font-bold mb-4">代码格式化工具</h1>
    <p class="text-gray-600 mb-6">支持多种编程语言的代码格式化，美化您的代码，提高可读性</p>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- 输入区域 -->
        <div class="border rounded-lg shadow-sm p-4 bg-white">
            <div class="flex justify-between items-center mb-3">
                <h2 class="text-xl font-semibold">输入代码</h2>
                <div class="space-x-2">
                    <button id="clearBtn" class="px-3 py-1 bg-gray-200 hover:bg-gray-300 rounded text-sm">清空</button>
                    <button id="loadSampleBtn" class="px-3 py-1 bg-blue-100 hover:bg-blue-200 rounded text-sm">加载示例</button>
                </div>
            </div>
            <textarea id="codeInput" class="w-full h-96 p-3 border rounded font-mono text-sm" placeholder="在此处粘贴您需要格式化的代码..."></textarea>
        </div>

        <!-- 输出区域 -->
        <div class="border rounded-lg shadow-sm p-4 bg-white">
            <div class="flex justify-between items-center mb-3">
                <h2 class="text-xl font-semibold">格式化后的代码</h2>
                <button id="copyBtn" class="px-3 py-1 bg-green-100 hover:bg-green-200 rounded text-sm">复制结果</button>
            </div>
            <textarea id="codeOutput" class="w-full h-96 p-3 border rounded font-mono text-sm bg-gray-50" placeholder="格式化后的代码将显示在这里..." readonly></textarea>
        </div>
    </div>

    <!-- 操作按钮 -->
    <div class="mt-6 bg-white p-4 border rounded-lg shadow-sm">
        <div class="flex flex-wrap gap-4 items-center">
            <div class="flex items-center">
                <span class="mr-2 font-medium">编程语言:</span>
                <select id="languageSelect" class="border rounded px-2 py-1">
                    <option value="javascript">JavaScript</option>
                    <option value="html">HTML</option>
                    <option value="css">CSS</option>
                    <option value="json">JSON</option>
                    <option value="python">Python</option>
                    <option value="java">Java</option>
                    <option value="csharp">C#</option>
                    <option value="php">PHP</option>
                    <option value="xml">XML</option>
                    <option value="sql">SQL</option>
                </select>
            </div>
            
            <div class="flex items-center">
                <span class="mr-2 font-medium">缩进:</span>
                <select id="indentSize" class="border rounded px-2 py-1">
                    <option value="2">2空格</option>
                    <option value="4">4空格</option>
                    <option value="8">8空格</option>
                </select>
            </div>
            
            <button id="formatBtn" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md">格式化代码</button>
        </div>
    </div>

    <!-- 高级设置 -->
    <div class="mt-6 bg-white p-4 border rounded-lg shadow-sm">
        <h2 class="text-xl font-semibold mb-3">高级设置</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <label class="inline-flex items-center mb-2">
                    <input type="checkbox" id="insertSpaces" class="form-checkbox h-4 w-4 text-blue-600" checked>
                    <span class="ml-2">使用空格代替制表符</span>
                </label>
                <label class="inline-flex items-center mb-2">
                    <input type="checkbox" id="bracketSpacing" class="form-checkbox h-4 w-4 text-blue-600" checked>
                    <span class="ml-2">括号内部添加空格</span>
                </label>
                <label class="inline-flex items-center">
                    <input type="checkbox" id="semicolons" class="form-checkbox h-4 w-4 text-blue-600" checked>
                    <span class="ml-2">添加分号</span>
                </label>
            </div>
            <div>
                <label class="inline-flex items-center mb-2">
                    <input type="checkbox" id="singleQuote" class="form-checkbox h-4 w-4 text-blue-600">
                    <span class="ml-2">使用单引号</span>
                </label>
                <label class="inline-flex items-center">
                    <input type="checkbox" id="trailingCommas" class="form-checkbox h-4 w-4 text-blue-600">
                    <span class="ml-2">添加尾随逗号</span>
                </label>
            </div>
        </div>
    </div>

    <!-- 使用说明 -->
    <div class="mt-6 bg-white p-4 border rounded-lg shadow-sm">
        <h2 class="text-xl font-semibold mb-3">使用说明</h2>
        <ul class="list-disc pl-5 space-y-2">
            <li>在左侧文本框中粘贴需要格式化的代码</li>
            <li>选择对应的编程语言和格式化选项</li>
            <li>点击"格式化代码"按钮</li>
            <li>格式化后的代码将显示在右侧文本框中</li>
            <li>您可以点击"复制"按钮复制格式化后的代码</li>
        </ul>
        <p class="mt-2 text-gray-600"><i class="fas fa-info-circle"></i> 提示：不同编程语言可能支持不同的格式化选项，部分选项可能不适用于某些语言。</p>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // DOM元素
        const codeInput = document.getElementById('codeInput');
        const codeOutput = document.getElementById('codeOutput');
        const formatBtn = document.getElementById('formatBtn');
        const clearBtn = document.getElementById('clearBtn');
        const copyBtn = document.getElementById('copyBtn');
        const loadSampleBtn = document.getElementById('loadSampleBtn');
        const languageSelect = document.getElementById('languageSelect');
        const indentSize = document.getElementById('indentSize');
        
        // 高级选项
        const insertSpaces = document.getElementById('insertSpaces');
        const bracketSpacing = document.getElementById('bracketSpacing');
        const semicolons = document.getElementById('semicolons');
        const singleQuote = document.getElementById('singleQuote');
        const trailingCommas = document.getElementById('trailingCommas');
        
        // 格式化代码
        formatBtn.addEventListener('click', function() {
            const code = codeInput.value.trim();
            if (!code) {
                showMessage('请输入需要格式化的代码');
                return;
            }
            
            const language = languageSelect.value;
            const indent = parseInt(indentSize.value);
            
            // 显示加载状态
            formatBtn.disabled = true;
            formatBtn.innerHTML = '<span class="inline-block animate-spin mr-2">↻</span> 正在格式化...';
            codeOutput.value = '正在处理...';
            
            // 准备请求数据
            const requestData = {
                code: code,
                language: language,
                indent: indent,
                insert_spaces: insertSpaces.checked,
                bracket_spacing: bracketSpacing.checked,
                semicolons: semicolons.checked,
                single_quote: singleQuote.checked,
                trailing_commas: trailingCommas.checked
            };
            
            // 发送API请求
            fetch('/tools/dev/code_formatter', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'auth': localStorage.getItem('token') || '' // 添加认证token
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                // 恢复按钮状态
                formatBtn.disabled = false;
                formatBtn.textContent = '格式化代码';
                
                if (data.error === 0) {
                    // 格式化成功
                    codeOutput.value = data.body.result;
                    
                    // 显示可能的提示信息
                    if (data.body.message) {
                        showMessage(data.body.message);
                    }
                } else {
                    // 格式化失败
                    codeOutput.value = '';
                    showMessage('错误: ' + (data.message || '格式化失败'));
                }
            })
            .catch(error => {
                formatBtn.disabled = false;
                formatBtn.textContent = '格式化代码';
                codeOutput.value = '';
                showMessage('请求失败: ' + error.message);
            });
        });
        
        // 清空输入
        clearBtn.addEventListener('click', function() {
            codeInput.value = '';
            codeOutput.value = '';
            codeInput.focus();
        });
        
        // 复制格式化后的代码
        copyBtn.addEventListener('click', function() {
            if (!codeOutput.value) {
                showMessage('没有可复制的内容');
                return;
            }
            
            codeOutput.select();
            document.execCommand('copy');
            
            const originalText = copyBtn.textContent;
            copyBtn.textContent = '已复制!';
            copyBtn.classList.add('bg-green-200');
            setTimeout(() => {
                copyBtn.textContent = originalText;
                copyBtn.classList.remove('bg-green-200');
            }, 1500);
        });
        
        // 加载示例代码
        loadSampleBtn.addEventListener('click', function() {
            const language = languageSelect.value;
            let sampleCode = '';
            
            switch (language) {
                case 'javascript':
                    sampleCode = 'function calculateSum(a,b) {\nreturn a+b;\n}\n\nconst result=calculateSum(10,20);\nconsole.log("The sum is: "+result);';
                    break;
                case 'html':
                    sampleCode = '<!DOCTYPE html><html><head><title>Sample Page</title></head><body><div class="container"><h1>Hello World</h1><p>This is a sample HTML code.</p></div></body></html>';
                    break;
                case 'css':
                    sampleCode = 'body{font-family:Arial,sans-serif;margin:0;padding:0;}.container{width:100%;max-width:1200px;margin:0 auto;}h1{color:#333;font-size:24px;}p{line-height:1.5;color:#666;}';
                    break;
                case 'json':
                    sampleCode = '{"name":"John Doe","age":30,"isEmployed":true,"skills":["JavaScript","HTML","CSS"],"address":{"city":"New York","zipCode":"10001"}}';
                    break;
                case 'python':
                    sampleCode = 'def calculate_sum(a, b):\n  return a + b\n\nresult = calculate_sum(10, 20)\nprint(f"The sum is: {result}")\n\nclass Person:\n  def __init__(self, name, age):\n    self.name = name\n    self.age = age\n\n  def greet(self):\n    print(f"Hello, my name is {self.name}")';
                    break;
                default:
                    sampleCode = '// 示例代码\n// 请选择具体的编程语言来查看对应的示例';
            }
            
            codeInput.value = sampleCode;
            codeOutput.value = '';
        });
        
        // 语言选择变化时更新高级选项
        languageSelect.addEventListener('change', function() {
            const language = languageSelect.value;
            
            // 根据不同语言调整可用的高级选项
            switch (language) {
                case 'javascript':
                case 'typescript':
                    enableAllOptions();
                    break;
                case 'html':
                case 'xml':
                    enableOption(insertSpaces);
                    enableOption(indentSize);
                    disableOption(bracketSpacing);
                    disableOption(semicolons);
                    disableOption(singleQuote);
                    disableOption(trailingCommas);
                    break;
                case 'python':
                    enableOption(insertSpaces);
                    enableOption(indentSize);
                    disableOption(bracketSpacing);
                    disableOption(semicolons);
                    disableOption(singleQuote);
                    disableOption(trailingCommas);
                    break;
                default:
                    enableAllOptions();
            }
        });
        
        // 辅助函数：启用选项
        function enableOption(element) {
            element.disabled = false;
            element.parentNode.classList.remove('text-gray-400');
        }
        
        // 辅助函数：禁用选项
        function disableOption(element) {
            element.disabled = true;
            element.parentNode.classList.add('text-gray-400');
        }
        
        // 辅助函数：启用所有选项
        function enableAllOptions() {
            enableOption(insertSpaces);
            enableOption(indentSize);
            enableOption(bracketSpacing);
            enableOption(semicolons);
            enableOption(singleQuote);
            enableOption(trailingCommas);
        }
        
        // 辅助函数：显示消息提示
        function showMessage(message) {
            // 创建消息提示元素
            let toast = document.createElement('div');
            toast.className = 'fixed bottom-4 right-4 bg-gray-800 text-white px-4 py-2 rounded shadow-lg transition-opacity duration-500';
            toast.style.opacity = '0';
            toast.textContent = message;
            
            // 添加到页面
            document.body.appendChild(toast);
            
            // 淡入效果
            setTimeout(() => {
                toast.style.opacity = '1';
            }, 10);
            
            // 淡出并移除
            setTimeout(() => {
                toast.style.opacity = '0';
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 500);
            }, 3000);
        }
        
        // 初始化页面
        languageSelect.dispatchEvent(new Event('change')); // 初始更新选项状态
    });
</script>
{% endblock %} 